import React, { useState, useEffect } from 'react';
import { proccessNames } from '../../services/pdProcess/pdProcess';
import { Button, Checkbox } from '@material-ui/core';
import api from '../../api';
import '../css/reportsChooser.css';
const createNode=(name)=>{
  let node={
    next:null,
    name:name,
    columns:[],
  }
  return{
    getNode:()=>node,
    getNext:()=>node.next,
    getName:()=>node.name,
    getColumns:()=>node.columns,
    setNext:(next)=>{node.next=next},
    setName:(value)=>{node.name=value},
    setColumns:(a)=>{node.columns=a},
    
  }
}
const SQLSchemaExplorer = () => {
  const [chosen,setChosen] = useState();
  const [update,setUpdate]=useState(false);
  const [props,setProps]=useState([]);
  const [reportName,setName]=useState("");
  useEffect(()=>setChosen(createNode('process')),[])
  const dataNames=["process","AWP","employee","ISPDN"];
  const sampleData = 
    {
      none:{name:'none',dictName:'none',columns:[],joined:'none'},
      process:{name:'Процесс',dictName:'process',
    columns:proccessNames,
  joined:'employee'}, 
    AWP:{name:'АРМ',dictName:'AWP',
    columns:[{name:"Имя",dictName:"name",type:"text"},{name:"Локация",dictName:"location",type:"text"},
    {name:"Тип",dictName:"type",type:"text"},{name:"Подразделение",dictName:"subdivision",type:"text"},{name:"ИСПДн",dictName:"ispdns",type:"text"}]
    ,joined:'ISPDN'
    }, employee:{name:'Сотрудник',dictName:'employee',
    columns:[{name:"Почта",dictName:"email",type:"text"},{name:"подразделение",dictName:"subdivision",type:"text"},
    {name:"Должность",dictName:"job",type:"text"},
    {name:"Имя",dictName:"name",type:"text"},
    {name:"Фамилия",dictName:"secondName",type:"text"},
    {name:"Отчество",dictName:"fatherName",type:"text"},
    {name:"АРМ",dictName:"awp",type:"text"}
    ],
    joined:'AWP'
    },ISPDN:{name:'ИСПДн',dictName:"ISPDN",
    columns:[{name:"Имя",dictName:"name",type:"text"},{name:"Уровень защиты",dictName:"defenceLevel",type:"text"},
    {name:"Трансграничная передеча",dictName:"overBorder",type:"checkbox"},{name:"Местоположение",dictName:"location",type:"text"}]
    ,joined:'none'}};

  const sendData=()=>{
   let arr=[];
   arr=getTree().map(e=>{
    return {
      entity:e.getName(),
      columns:e.getColumns(),
    }
  });
  let res={
    reportInfo:{
    name:reportName,
    address:"",
    reportProperties:props,
  },
    query:arr,
  }
  console.log(res);
  api.post("/PDP/reports/create",res);

  }
  const handleTableChange=(e,node)=>{
    node.setNext(null);
    node.setName(e.target.value);
    node.setColumns([]);
    setChosen({...chosen});
    setUpdate(!update);
  }
  const handleColumnChange = (e,node,i) => {
   const value=e.target.value;
   node.getColumns()[i]=value;
   setChosen({...chosen});
   setUpdate(!update);
  }; 

  const getTree=()=>{
    let arr=[];
    let node=chosen;
    while(node){
      arr.push(node);
      node=node.getNext();
    }
    return arr;
  }
  const addColumn=(node)=>{
    node.getColumns().push(sampleData[node.getName()].columns[0].dictName);
    setChosen({...chosen});
  }
  const addTable=()=>{
    let arr=getTree();
    let last=arr[arr.length-1];
    if(sampleData[last.getName()].joined==='none')
      return;
    last.setNext(createNode(sampleData[last.getName()].joined));
    setChosen({...chosen});
    setUpdate(!update);
  }
  const addProperty=(checked,node,i)=>{
    let val;
    sampleData[node.getName()].columns.map(e=>{
      if(e.dictName===node.getColumns()[i])
        val=e;
    });
    
    val={...val,dictName:node.getName()+"_"+val.dictName}
    if (checked)
    {
        setProps([...props,val]);
        return;
    }
    else{
      let array=props;
      const index = array.indexOf(val);
    if (index > -1) { 
    array.splice(index, 1); 
  }
  setProps(array);
    }
  }


  return (
    <div>
    <input placeholder='Имя отчета' onChange={(e)=>{setName(e.target.value)}}></input>
      <select onChange={(e)=>handleTableChange(e,chosen)}>
        {dataNames.map(data=><option key={sampleData[data].name}value={sampleData[data].dictName}>{sampleData[data].name}</option>)}
        </select>
        {getTree().map((node,j)=>{
      return (<div key={j}>
        <label >{sampleData[node.getName()].name}</label>
        {node.getColumns().map((column,i)=>
         <div key={i}  className='column'>
          <select onChange={(e)=>handleColumnChange(e,node,i)}>
          {sampleData[node.getName()].columns.map((column,k)=><option key={k} value={column.dictName}>{column.name}</option>)}
          </select>
          <Checkbox onChange={(e,checked)=>addProperty(checked,node,i)}></Checkbox>
          </div>
        )
      }
  
   <Button className='reportButton' onClick={()=>addColumn(node)}>+</Button>

   </div> 
     
  )
      }
      )
      }
     <Button className='reportButton' onClick={addTable}>+#</Button>
      <Button className='reportButton' onClick={sendData}>Save</Button>
 
    </div>
  );
};

export default SQLSchemaExplorer;